package com.earogya.logic.pharmacy.prescription;

import java.util.Calendar;

import org.apache.struts.pharmacy.pharmacy.model.PrescriptionDrugs;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.DataTypeException;
import ca.uhn.hl7v2.model.v251.message.RDE_O11;

public class CreateRDEO11 {

	private RDE_O11 adt;
	private PrescriptionDrugs request;
	
	public CreateRDEO11(PrescriptionDrugs request){
		this.adt=new RDE_O11();
		this.request=request;
	}
	
	public String createMessage(String sendingFacility) throws HL7Exception{
		this.addMessageHeader(sendingFacility);
		this.addPatientDetails();
		this.addOrderDetails();
		this.addDrugDetails();
		return adt.getMessage().encode();
	}
	
	private void addMessageHeader(String sendingFacility) throws DataTypeException{
		adt.getMSH().getFieldSeparator().setValue("|");
		adt.getMSH().getEncodingCharacters().setValue("^~\\&");
		adt.getMSH().getDateTimeOfMessage().getTime().setValue(Calendar.getInstance().getTime());
		adt.getMSH().getMessageType().getMsg1_MessageCode().setValue("RDE");
		adt.getMSH().getMessageType().getTriggerEvent().setValue("O11");
		adt.getMSH().getSendingApplication().getUniversalID().setValue("CSTH");
		adt.getMSH().getVersionID().getVersionID().setValue("2.5.1");
		adt.getMSH().getSendingFacility().getUniversalID().setValue(sendingFacility);
		adt.getMSH().getReceivingApplication().getUniversalID().setValue("PAS");
		adt.getMSH().getReceivingFacility().getUniversalID().setValue(sendingFacility);
	}
	
	private void addOrderDetails() throws DataTypeException{
		adt.getORDER().getORC().getOrc2_PlacerOrderNumber().getEi1_EntityIdentifier().setValue(request.getRequestId());
		adt.getORDER().getORC().getOrc7_QuantityTiming(0).getQuantity().getCq1_Quantity().setValue(request.getQuantity());
		adt.getORDER().getORC().getDateTimeOfTransaction().getTime().setValue(request.getRequestDate());
		adt.getORDER().getORC().getOrc10_EnteredBy(0).getIDNumber().setValue(request.getPrescribedByID());
		}

	private void addDrugDetails() throws DataTypeException {
		adt.getORDER().getRXE().getRxe2_GiveCode().getCe1_Identifier().setValue(request.getDrugId());
		adt.getORDER().getRXE().getGiveAmountMinimum().setValue(request.getMinAmount());
		adt.getORDER().getRXE().getGiveAmountMaximum().setValue(request.getMaxAmount());
		adt.getORDER().getRXE().getGiveUnits().getCe1_Identifier().setValue(request.getAmountUnits());
		adt.getORDER().getRXE().getGiveDosageForm().getCe1_Identifier().setValue(request.getDosage());
		adt.getORDER().getRXE().getSubstitutionStatus().setValue(request.getAllowSubstitutes());
		adt.getORDER().getRXE().getPrescriptionNumber().setValue(request.getPrescriptionNo());
		}

	private void addPatientDetails() throws DataTypeException {
		adt.getPATIENT().getPID().getPid2_PatientID().getCx1_IDNumber().setValue(request.getPatientId());	
	}
	
}
